﻿//------------------------------------------------------------------------------ 
// <copyright file="JMask.cs" company="Fm Computer">
//     Copyright (c) Fm Computer di Menatti Fulvia.  All rights reserved.
// </copyright>
//----------------------------------------------------------------------------- 
namespace FmjQuery
{
    using System;
    using System.ComponentModel;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    /// <summary>
    /// Add Edit Mask to Target Control
    /// </summary>
    [ToolboxData("<{0}:JMask runat=server />")]
    [DefaultProperty("TargetControlID")]
    [NonVisualControl]
    public class JMask : JQueryExtendControl
    {
        #region Field
        /// <summary>
        /// Collection of definition
        /// </summary>
        private MaskDefinitions tdefinitions;

        /// <summary>
        /// Collection of replace definitions
        /// </summary>
        private MaskReplaceDefinitions treplaces;
        #endregion

        #region Costruct
        /// <summary>
        /// Initializes a new instance of the JMask class.
        /// </summary>
        public JMask()
        {
            this.IsRenderControl = false;
        }
        #endregion

        #region Property
        /// <summary>
        /// Gets or sets Edit Mask
        /// </summary>
        public string EditMask
        {
            get; 
            set;
        }

        /// <summary>
        /// Gets or sets Replace Mask
        /// </summary>
        public string ReplaceMask
        {
            get; 
            set;
        }

        /// <summary>
        /// Gets or sets Holder
        /// </summary>
        public char Holder
        {
            get; set;
        }

        /// <summary>
        /// Gets or sets id of button that replace content of target Control
        /// </summary>
        public string ButtonIDReplace
        {
            get; 
            set;
        }

        /// <summary>
        /// Gets list of definitions
        /// </summary>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public MaskDefinitions Definitions
        {
            get
            {
                if (this.tdefinitions == null)
                {
                    this.tdefinitions = new MaskDefinitions();
                }

                return this.tdefinitions;
            }
        }

        /// <summary>
        /// Gets list of replace definition
        /// </summary>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public MaskReplaceDefinitions ReplaceDefinitions
        {
            get
            {
                if (this.treplaces == null)
                {
                    this.treplaces = new MaskReplaceDefinitions();
                }

                return this.treplaces;
            }
        }
        #endregion

        #region Overrides of JQueryExtendControl
        /// <summary>
        /// Return list of webResource
        /// </summary>
        /// <returns>web resources</returns>
        public override JWebSources GetResources()
        {
            return null;
        }

        /// <summary>
        /// Gets list of css image resources
        /// </summary>
        /// <returns>list of images</returns>
        public override CssResources GetCssResources()
        {
            return null;
        }

        /// <summary>
        /// Gets list of client nameSpace
        /// </summary>
        /// <returns>list of namespace</returns>
        public override ClientNameSpaces GetClientNameSpace()
        {
            return null;
        }

        /// <summary>
        /// Create jQuery control
        /// </summary>
        public override void CreateJControl()
        {
            Manager.EditMask = true;

            if (this.Enabled)
            {
                // check property
                if (string.IsNullOrEmpty(this.EditMask))
                {
                    throw new InvalidOperationException("You must set EditMask");
                }

                // create script
                StringBuilder builder = new StringBuilder();

                // create definitions
                foreach (MaskDefinition definition in this.Definitions)
                {
                    builder.AppendFormat("$.Mask.Definitions['{0}'] = '[{1}", definition.Name, definition.Value);

                    if (definition.IncludeHolder)
                    {
                        builder.Append("' + ");

                        if (this.Holder.Equals(char.MinValue))
                        {
                            builder.Append("$.Mask.Holders['all']");
                        }
                        else
                        {
                            builder.AppendFormat("'{0}'", this.Holder);
                        }

                        builder.Append(" + '");
                    }

                    builder.Append("]';");
                }

                foreach (MaskDefinition definition in this.ReplaceDefinitions)
                {
                    builder.AppendFormat("$.Mask.ReplaceDefinitions['{0}'] = '[{1}]';", definition.Name, definition.Value);
                }

                // create mask
                builder.AppendFormat("$('#{0}').mask('{1}'", this.TargetControlClientID, this.EditMask);

                if (!string.IsNullOrEmpty(this.ReplaceMask) || !this.Holder.Equals(char.MinValue))
                {
                    bool first = true;

                    builder.Append(",{");
                    if (!string.IsNullOrEmpty(this.ReplaceMask))
                    {
                        builder.AppendFormat("replaceText: '{0}'", this.ReplaceMask);
                        first = false;
                    }

                    if (!this.Holder.Equals(char.MinValue))
                    {
                        if (!first)
                        {
                            builder.Append(",");
                        }

                        builder.AppendFormat("holder: '{0}'", this.Holder);
                    }

                    builder.Append("}");
                }

                builder.Append(");");

                // create script for replace button
                if (!string.IsNullOrEmpty(this.ButtonIDReplace))
                {
                    Control c = FindControl(this.ButtonIDReplace);

                    if (c == null)
                    {
                        throw new InvalidOperationException("Don't find Button Replace");
                    }

                    Type tc = c.GetType();
                    bool isLink = tc == typeof(LinkButton);
                    bool isButton = tc == typeof(Button);
                    bool isImage = tc == typeof(ImageButton);

                    if (isLink || isButton || isImage)
                    {
                        string script = string.Format("$('#{0}').replaceWithOutMask();", this.TargetControlClientID);

                        if (isLink)
                        {
                            ((LinkButton) c).OnClientClick += script;
                        }
                        else
                            if (isButton)
                            {
                                ((Button) c).OnClientClick += script;
                            }
                            else
                            {
                                ((ImageButton) c).OnClientClick += script;
                            }
                    }
                    else
                    {
                        builder.AppendFormat("$('#{0}').bind('click', null,function()", c.ClientID);
                        builder.Append("{");
                        builder.AppendFormat("$('#{0}').replaceWithOutMask();", this.TargetControlClientID);
                        builder.Append("})");
                    }
                }

                Utility.RegisterStartUpScript(this.Page, string.Concat("mask_", this.ClientID), builder.ToString());
            }
        }
        #endregion
    }
}
